package com.apes.scm.settle.settle.service;

import com.apes.framework.query.ApesDao;
import com.apes.framework.util.DateUtil;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.Date;
import java.util.List;
import java.util.Map;

/*
 * 采购结算
 * */
@Component
public class SettleReceivableDao extends ApesDao {
    @Autowired
    EntityManager entityManager;

    /**
     * 查询收入汇总
     *
     * @return
     */
    public List<Map> queryIncome() {
        //货币资金 应收账款 跨公司消费 取销售报表数据
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT  a.company_id, a.partner_id, a.inventory_mode\n" +
                "  FROM acc_ledger a  where 1 = 1 group by a.company_id, a.partner_id, a.inventory_mode");
        Query query = entityManager.createNativeQuery(sb.toString());
        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return query.getResultList();
    }

    /**
     * @param companyId
     * @param partnerId
     * @param dateStart
     * @return
     */
    public List<Map> queryCompanyPartner(String companyId, String partnerId, String inventoryMode, Date dateStart) {
        //货币资金 应收账款 跨公司消费 取销售报表数据
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT b.amount\n" +
                "  FROM acc_ledger a, acc_ledger_entry b\n" +
                " where a.id = b.ledger_id\n" +
                "   and a.ledger_account_id = 'current_unsettled'\n" +
                "   and a.company_id = :COMPANY_ID\n" +
                "   and a.partner_id = :PARTNER_ID" +
                "   and a.inventory_mode =:INVENTORY_MODE" +
                "   and  b.create_date < to_date(:DATE_START, 'yyyy-mm-dd')\n" +
                " order by b.create_date desc\n");
        Query query = entityManager.createNativeQuery(sb.toString());
        query.setParameter("DATE_START", DateUtil.format(dateStart, DateUtil.SHOW_DATE_FORMAT));
        query.setParameter("COMPANY_ID", companyId);
        query.setParameter("PARTNER_ID", partnerId);
        query.setParameter("INVENTORY_MODE", inventoryMode);
        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return query.getResultList();
    }
}

